package com.iphanta.community.common;

import com.baidu.fsg.uid.UidGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author 墨声 E-mail: zehong.hongframe.huang@gmail.com
 * create time: 3/7/22 6:26 PM
 */
@Component
public class RequestIdInterceptor implements HandlerInterceptor {

    private final static String REQUEST_ID = "requestId";
    private static final Logger LOGGER = LoggerFactory.getLogger(RequestIdInterceptor.class);

    @Autowired
    private UidGenerator uidGenerator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String attr = (String) request.getSession().getAttribute(REQUEST_ID);
        String uid = request.getHeader("USER_ID");
        UserUtils.setUid(uid);

        if(Objects.isNull(attr)) {
            Long requestId = uidGenerator.getUID();
            MDC.put(REQUEST_ID, String.valueOf(requestId));
            request.getSession().setAttribute(REQUEST_ID, String.valueOf(requestId));
            LOGGER.info("request id:{}, client ip:{}, X-Forwarded-For:{}, request URI: {}",
                    requestId, request.getRemoteAddr(), request.getHeader("X-Forwarded-For"), request.getRequestURI());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(REQUEST_ID);
        String attr = (String) request.getSession().getAttribute(REQUEST_ID);
        request.getSession().removeAttribute(REQUEST_ID);
        response.addHeader("REQUEST_ID", attr);
        UserUtils.remove();
        LOGGER.info("remove requestId ({}) from logger", attr);

    }

}
